//
//  HELCompulsoryVC.m
//  sanda
//
//  Created by 陈武琦 on 16/7/12.
//  Copyright © 2016年 陈武琦. All rights reserved.
//
/*
 *          必修／选修
 */
 
typedef NS_ENUM(NSInteger, HELStatusType) {
    HELStatusTypeUnbegin = 0,//0未开始
    HELStatusTypeGoing = 1,//1进行中
    HELStatusTypeCompeleted = 2 //2已完成
    
};
typedef NS_ENUM(NSInteger, HELSortType) {
    HELSortTypeProgress = 1,//1按进度 2按最新 3按热度
    HELSortTypeNew = 2
};

#import "HELCompulsoryVC.h"
#import "HELCompulsoryCell.h"
#import "HELUserInfoM.h"
#import "HELCourseDetailVC.h"
#import "Masonry.h"
#import "HELSuperTableView.h"
#import "CWQ_PopView.h"
#import "CWQ_tableView.h"
#import "BTCollectionBottomMenuView.h"

@interface HELCompulsoryVC ()<UITableViewDelegate, CWQ_PopViewDelegate,BTCollectionBottomMenuViewViewDelegate>
@property(nonatomic, copy)NSArray* dataSource;

@property(nonatomic, strong)CWQ_tableView *tableView;
//选修、必修
@property (nonatomic, assign) HELCourseType type;
//选状态
@property (nonatomic, assign) HELStatusType statusType;
//排序
@property (nonatomic, assign) HELSortType sortType;
//点击状态，排序
@property (nonatomic, assign) NSInteger btnIndex;
@property(nonatomic, strong)BTCollectionBottomMenuView *bottomMenu;
@property (nonatomic, copy) NSMutableDictionary *deleteDic;
@property (weak, nonatomic) IBOutlet UIButton *stateBtn;
@property (weak, nonatomic) IBOutlet UIButton *sortBtn;
@property(nonatomic, strong) CWQ_PopView *popView;

@end
static NSString *cellID = @"HELCompulsoryCellID";
@implementation HELCompulsoryVC

- (instancetype)initWithType:(HELCourseType)type {
    if (self = [super init]) {
        _type = type;
        _statusType = -1;
    }

    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self titleView:self.title];
    self.view.backgroundColor = [UIColor  whiteColor];
    [self setupSubviews];
    
}

- (void)setupSubviews {
    CWQ_tableView *tableView = [[CWQ_tableView alloc] initWithFrame:CGRectMake(0, 44, kScreenWidth, kScreenHeight - 108) style:UITableViewStylePlain cellClass:@"HELCompulsoryCell" vc:self upload:NO];
    [self.view addSubview:tableView];
    _tableView = tableView;
    _dataSource = [[NSArray alloc] init];
    [_tableView cwq_requestDataWithDown:YES];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(44, 0, 0, 0));
    }];

    if (self.type == HELcourseTypeCollectStatus) {
        UIButton *rightItemBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
        [rightItemBtn setImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
        rightItemBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [rightItemBtn addTarget:self action:@selector(deleteClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:rightItemBtn]];
        defineWeakSelf;
        [self.bottomMenu mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.size.mas_equalTo(CGSizeMake(kScreenWidth+2, 44));
            make.left.equalTo(weakSelf.view).with.offset(0);
            make.top.equalTo(weakSelf.tableView.mas_bottom).with.offset(0);
            
        }];
        
    }

}

- (void)deleteClick:(UIButton *)btn {
    self.tableView.editing = !self.tableView.editing;
    if (self.tableView.editing) {
        [btn setImage:nil forState:UIControlStateNormal];
        [btn setTitle:@"取消" forState:UIControlStateNormal];
        [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 44, 0));
        }];
    }else {
        
        [btn setImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
        [btn setTitle:@"" forState:UIControlStateNormal];
        [self.deleteDic removeAllObjects];
        [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(44, 0, 0, 0));
        }];
    }
}


- (BTCollectionBottomMenuView *)bottomMenu {
    if (!_bottomMenu) {
        _bottomMenu = [BTCollectionBottomMenuView menuView];
        _bottomMenu.delegate = self;
        [self.view addSubview:_bottomMenu];
    }
    
    return _bottomMenu;
    
}


- (void)setDataSource:(NSArray *)dataSource {
    _dataSource = dataSource;
    [self.tableView setupSourceArray:dataSource];
}

- (NSMutableDictionary *)deleteDic {
    
    if (!_deleteDic) {
        _deleteDic = [@{} mutableCopy];
    }
    
    return _deleteDic;
}


- (void)cwq_tableView:(CWQ_tableView *)tableView requestDataWithDown:(BOOL)down {
    
    self.tableView.loading = YES;
    helUserInfo
    NSMutableDictionary *param = [@{@"requiredStatus":@1, @"userId":userInfo.userId} mutableCopy];
    if (self.type == HELcourseTypeCollectStatus) {
        param = [@{@"collectStatus":@1, @"userId":userInfo.userId} mutableCopy];
        
    }
    if (self.statusType >= 0) {
        param[@"status"] = @(self.statusType);
    }
    
    if (self.sortType > 0) {
        param[@"sortType"] = @(self.sortType);
    }else {
        param[@"sortType"] = @(HELSortTypeNew);
    }
    
    defineWeakSelf;
    [[HELNetworkManager sharedMg] POST:helCompulsoryUrl parameters:param success:^(id responseObject) {
        if (responseObject[@"exception"]) {
            cwqHudRequestError(responseObject[@"exception"]);
        }else {
            NSMutableArray *arr = [HELCompulsoryM mj_objectArrayWithKeyValuesArray:responseObject[@"rows"]];
            weakSelf.dataSource = arr;
            [weakSelf.tableView.header endRefreshing];
            
            if (weakSelf.dataSource.count<=0) {
                weakSelf.tableView.loading = NO;
            }
        }
    } failure:^(NSString *err) {
        
        [weakSelf.tableView.header endRefreshing];
        if (weakSelf.dataSource.count<=0) {
            self.tableView.footer.hidden = YES;
        }else {
            self.tableView.footer.hidden = NO;
        }
        cwqHudRequestError(err);
        if (weakSelf.dataSource.count<=0) {
            weakSelf.tableView.loading = NO;
        }
    }];
}


- (IBAction)stateBtnClick:(id)sender {
    
    if (_popView.tag == 10001 && !(_popView.superview == nil)) {
        [_popView removeFromSuperview];
        _popView = nil;
        return;
    }
    [_popView removeFromSuperview];
    _popView = nil;
    _popView = [[CWQ_PopView alloc] initWithFrame:self.tableView.frame titlesArray:@[@"全部状态", @"未开始", @"进行中",@"已完成"] selectIndex:self.statusType+1 delegate:self];
    _popView.tag = 10001;
    if (self.statusType == (-1)) {
        self.popView.selectRow = 0;
    }
    [self.popView showInView:self.view];
}




- (IBAction)sortBtnClick:(id)sender {
    if (_popView.tag == 10002 && !(_popView.superview == nil)) {
        [_popView removeFromSuperview];
        _popView = nil;
        return;
    }
    [_popView removeFromSuperview];
    _popView = nil;
    
    _popView = [[CWQ_PopView alloc] initWithFrame:self.tableView.frame titlesArray:nil selectIndex:0 delegate:self];
    _popView.tag = 10002;
    [self.popView setTitleS:@[@"按最新", @"按进度"]];
    self.popView.selectRow = self.sortType;
    [self.popView showInView:self.view];
    
}

- (void)CWQ_PopView:(CWQ_PopView *)popView didSelectRowAtIndexPath:(NSInteger)indexPath title:(NSString *)title {

    if (popView.tag == 10001) {
        [self.stateBtn setTitle:title forState:UIControlStateNormal];
        self.statusType = indexPath - 1;
    }else if (popView.tag == 10002){
    
        [self.sortBtn setTitle:title forState:UIControlStateNormal];
        self.sortType = indexPath;
    }
    _btnIndex = 0;
    [self.tableView cwq_requestDataWithDown:YES];
}

#pragma mark - <UITableViewData and UITableDelegate>

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HELCompulsoryCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    HELCompulsoryM *model = self.dataSource[indexPath.row];
    cell.model = model;
    if (self.type == HELcourseTypeCollectStatus) {
        cell.isNew.hidden = YES;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.editing) {
        HELCompulsoryM *model = [self.dataSource objectAtIndex:indexPath.row];
        [self.deleteDic setObject:model forKey:model.tblStudyDataId];
        [self resetDeleteBtnTitle];
        return;
    }
     HELCompulsoryM *model = self.dataSource[indexPath.row];
     HELCourseDetailVC *courseDetailVC = [HELCourseDetailVC new];
    if (self.type == HELcourseTypeRequiredStatus) {
        courseDetailVC.isFromRequiedCourse = YES;
    }
    weakSelf_define;
     courseDetailVC.courseId = [model.tblStudyDataId integerValue];
    courseDetailVC.callBack = ^(HELCourseDetailModel *model){
        [weakSelf.tableView cwq_requestDataWithDown:YES];
    };
    
     [self.navigationController pushViewController:courseDetailVC animated:YES];
}

- (void)resetDeleteBtnTitle {
    
    NSString *deleTitle;
    if ([self.deleteDic count] == 0) {
        deleTitle = @"删除";
    }else {
        
        deleTitle = [NSString stringWithFormat:@"删除(%zd)",[self.deleteDic count]];
    }
    [self.bottomMenu.deleteBtn setTitle:deleTitle forState:UIControlStateNormal];
    
}


- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.editing) {
        HELCompulsoryM *model = [self.dataSource objectAtIndex:indexPath.row];
        [self.deleteDic removeObjectForKey:model.tblStudyDataId];
        [self resetDeleteBtnTitle];

    }
}

#pragma mark ----------------bottomMenu代理--------------------------
- (void)cwqMenuView:(BTCollectionBottomMenuView *)menuView clickSelectBtn:(UIButton *)button {
    if ([button.titleLabel.text isEqualToString:@"全选"]) {
        [button setTitle:@"全不选" forState:UIControlStateNormal];
        for (int i = 0; i < self.dataSource.count; i++) {
            HELCompulsoryM *model = [self.dataSource objectAtIndex:i];
            [self.deleteDic setObject:model forKey:model.tblStudyDataId];
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES scrollPosition:NO];
            
        }
    }else {
        [button setTitle:@"全选" forState:UIControlStateNormal];
        for (int i = 0; i < self.dataSource.count; i++) {
            HELCompulsoryM *model = [self.dataSource objectAtIndex:i];
            [self.deleteDic removeObjectForKey:model.tblStudyDataId];
            [self.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES];
            
        }
    }
    [self resetDeleteBtnTitle];
}

- (void)cwqMenuView:(BTCollectionBottomMenuView *)menuView clickDeleteBtn:(UIButton *)button {
    [self cancelCollectionIds:[self.deleteDic allKeys]];
    if ([self.deleteDic count] == self.dataSource.count) {
        [self.deleteDic removeAllObjects];
        NSMutableArray *muA = [NSMutableArray arrayWithArray:self.dataSource];
        [muA removeAllObjects];
        self.dataSource = [muA copy];
        [button setTitle:@"删除" forState:UIControlStateNormal];
        return;
    }
    
    NSMutableArray *muA = [self.dataSource mutableCopy];
    [muA removeObjectsInArray:[self.deleteDic allValues]];
    [self.deleteDic removeAllObjects];
    self.dataSource = [muA copy];
    [button setTitle:@"删除" forState:UIControlStateNormal];

}

#pragma mark - 取消收藏-------
- (void)cancelCollectionIds:(NSArray *)ids{
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    cwqHud(self.view);
    params[@"ids"] = [self jsonStringWithArray:ids];
    params[@"userId"]=HEL_USERID;
    [[HELNetworkManager sharedMg] GET:kCourseCollect_url parameters:params success:^(id responseObject) {
        if ([responseObject isKindOfClass:[NSArray class]]) {
            cwqHudSuccess(hud);
        }else {
            if (responseObject[@"exception"]) {
                cwqAlertMessage(responseObject[@"exception"]);
            }
        }
        
    } failure:^(NSString *err) {
        [hud hideAnimated:YES];
    }];
    
}

-(id) jsonStringWithArray:(NSArray *)array{
    NSString *string = [NSString stringWithFormat:@"%@",array];
    NSString * str = [string stringByReplacingOccurrencesOfString:@"(" withString:@"["];
    NSString *str2 = [str stringByReplacingOccurrencesOfString:@")" withString:@"]"];
    return str2;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
